#include "widget_log_text.h"
#include <QMenu>

WidgetLogText::WidgetLogText(QWidget *parent)
    : QTextEdit{parent}
{
    _fmtDebug.setForeground(Qt::darkGray);
    _fmtInfo.setForeground(QColor::fromRgb(0x00A020));
    _fmtWarn.setForeground(QColor::fromRgb(0xD19B06));
    _fmtError.setForeground(Qt::red);

    _contextMenu = new QMenu(this);
    _actionSelect = new QAction(tr("全选"), this);
    _actionCopy = new QAction(tr("复制"), this);
    _actionClear = new QAction(tr("清空"), this);
    _contextMenu->addAction(_actionSelect);
    _contextMenu->addAction(_actionCopy);
    _contextMenu->addAction(_actionClear);

    connect(_actionSelect, &QAction::triggered, this, &QTextEdit::selectAll);
    connect(_actionCopy, &QAction::triggered, this, &QTextEdit::copy);
    connect(_actionClear, &QAction::triggered, this, &QTextEdit::clear);
    connect(this, &QTextEdit::customContextMenuRequested, this, &WidgetLogText::on_customContextMenuRequested);
    setContextMenuPolicy(Qt::CustomContextMenu);
}

void WidgetLogText::showMessage(const QString& header, const QString& content)
{
    QChar logLevel = header.at(header.length() - 2);
    switch (logLevel.toLatin1())
    {
    case 'D': this->mergeCurrentCharFormat(_fmtDebug); break;
    case 'I': this->mergeCurrentCharFormat(_fmtInfo); break;
    case 'W': this->mergeCurrentCharFormat(_fmtWarn); break;
    case 'E': this->mergeCurrentCharFormat(_fmtError); break;
    }
    this->append(header + ">> " + content);
}

void WidgetLogText::on_customContextMenuRequested(const QPoint &pos)
{
    _contextMenu->exec(QCursor::pos());
}
